package com.yuanduan.mplus.view;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cj.framework.app.BaseActivity;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.IOkHttp;
import com.cj.framework.util.Msg;
import com.cj.framework.util.OkHttpImp;
import com.cj.framework.util.RSAUtils;
import com.cj.framework.util.SP;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.db.dao.UserDao;
import com.yuanduan.mplus.model.entity.RS;

import java.util.HashMap;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_userPhone;
    private EditText et_userPwd;
    private TextView tv_login;
    private TextView tv_touristLogin;
    private ImageButton ib_cancel;
    private CheckBox cb_remember;
    private TextView tv_remember;
    private TextView tv_forget;

    ProgressDialog progressDialog;
    private String userPhone;
    private String userPwd;
    private IOkHttp iOkHttp;
    private UserDao userDao;
    private IOkHttp.IHttpCallback icallback=new IOkHttp.IHttpCallback() {
        @Override
        public void onResponse(Msg msg, int index) {
            String message=msg.content();
            switch(index){
                case 0:
                    dealwithVerify(message);
                    break;
                case 1:
                    dealwithUserInfo(message);
                    break;
            }
        }

        @Override
        public void onError(Exception e) {
            Toast.makeText(LoginActivity.this,"网络不佳",Toast.LENGTH_SHORT).show();
        }
    };

    private void dealwithUserInfo(String message) {
        String str=RSAUtils.decryptWithRSA(message);
        Log.d("xx",str);
        progressDialog.dismiss();
        com.yuanduan.mplus.db.entity.User user= (com.yuanduan.mplus.db.entity.User) Config.decry(message,com.yuanduan.mplus.db.entity.User.class);
        if(user.getRS()!=1){
            Toast.makeText(LoginActivity.this,"登录失败，请重新尝试",Toast.LENGTH_SHORT).show();
            return;
        }
        user.setUserPwd(userPwd);
        userDao.insert(user);
        openActivity(Main1Activity.class);
    }

    private void dealwithVerify(String message) {
        //检测rs
        String mm=RSAUtils.decryptWithRSA(message);
        RS rs= (RS) Config.decry(message,RS.class);
        if(rs==null){
            Toast.makeText(LoginActivity.this,"验证用户身份失败",Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
            return;
        }
        if(rs.getRs()!=1){
            progressDialog.dismiss();
            Toast.makeText(LoginActivity.this,"用户名或者密码错误",Toast.LENGTH_SHORT).show();
            return;
        }

        //记住密码功能
        if(cb_remember.isChecked()){
            SP.add("isRemember",true);
            SP.add("rememberUserPhone",userPhone);
            SP.add("rememberUserPwd",userPwd);
        }else{
            SP.add("isRemember",false);
        }

        //请求用户信息数据,保存至数据库
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",userPhone);
        hashMap.put("UserPassword",userPwd);
        hashMap.put("TargetUserPhone",userPhone);
        iOkHttp.httpInfoPost(Config.URL+Config.USERINFO,Config.translateMap(hashMap),icallback,1);
        progressDialog.setMessage("正在登录");
    }


    @Override
    protected void findId() {
        tv_forget= (TextView) findViewById(R.id.login_tv_forget);
        tv_remember= (TextView) findViewById(R.id.login_tv_remember);
        cb_remember= (CheckBox) findViewById(R.id.login_cb_remember);
        et_userPhone = (EditText) findViewById(R.id.login_et_phone);
        et_userPwd= (EditText) findViewById(R.id.login_et_pwd);
        tv_login= (TextView) findViewById(R.id.login_tv_login);
        tv_touristLogin= (TextView) findViewById(R.id.login_tv_touristlogin);
        ib_cancel= (ImageButton) findViewById(R.id.login_ib_cancel);
    }

    @Override
    protected void logic() {
        //添加监听器；
        tv_login.setOnClickListener(this);
        tv_touristLogin.setOnClickListener(this);
        ib_cancel.setOnClickListener(this);
        cb_remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    tv_remember.setTextColor(getResources().getColor(R.color.blue1));
                }else{
                    tv_remember.setTextColor(getResources().getColor(android.R.color.black));
                }
            }
        });
        tv_forget.setOnClickListener(this);
        userDao=BaseApplication.getDaoSession().getUserDao();
        progressDialog=new ProgressDialog(this);

        //按钮颜色改变
        et_userPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if(et_userPhone.getText().toString().trim().length()>0&&s.length()>0){
                    tv_login.setBackgroundResource(R.drawable.btn_login1);
                }else{
                    tv_login.setBackgroundResource(R.drawable.login_tv1);
                }
            }
        });

        //是否填写用户信息
        boolean isRemember=SP.getBoolean("isRemember");
        if(isRemember){
            et_userPhone.setText(SP.getString("rememberUserPhone"));
            et_userPwd.setText(SP.getString("rememberUserPwd"));
            cb_remember.setChecked(true);
        }
        iOkHttp=new OkHttpImp();
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.login_tv_login:
                login();
                break;
            case R.id.login_tv_touristlogin:
                com.yuanduan.mplus.db.entity.User user=new com.yuanduan.mplus.db.entity.User();
                user.setRealName("游客");
                user.setUserType("3");
                userDao.insert(user);
                openActivity(Main1Activity.class);
                this.finish();
                break;
            case R.id.login_ib_cancel:
                this.finish();
                break;
            case R.id.login_tv_forget:
                openActivity(ResetPwdActivity.class);
                break;
        }
    }

    private void login(){
        userPhone= et_userPhone.getText().toString().trim();
        userPwd=et_userPwd.getText().toString().trim();
        //账户密码合理性
        if(!checkUser(userPhone,userPwd)){
            Toast.makeText(this,"请输入正确的账户名和密码",Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog.setTitle("正在登陆");
        progressDialog.show();

        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",userPhone);
        hashMap.put("UserPassword",userPwd);
        iOkHttp.httpInfoPost(Config.URL+Config.VERIFYUSER,Config.translateMap(hashMap),icallback,0);
    }

    private boolean checkUser(String userPhone,String userPwd){
        if(TextUtils.isEmpty(userPhone)||TextUtils.isEmpty(userPwd)){
            return false;
        }
        return true;
    }
}
